package com.xinyu126.net_trace.listener

import android.content.Context
import android.location.Location
import android.util.Log
import com.magical.location.LocationDatabaseManager
import com.magical.location.client.LocationListener
import com.magical.location.internal.LocationDao
import com.magical.location.model.SyncTrace
import com.xinyu126.net_trace.Util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

class NetTraceListener(context: Context) : LocationListener {

    private var syncTraceId: Long = -1L
    private val locationDao: LocationDao = LocationDatabaseManager(context).getDAO()

    private fun getSyncTrace(): SyncTrace {
        //UUID 先本地获取,如果本地没有,则生成一个
        var trace = locationDao.getSyncTrace()
        if(trace == null || trace.clientId.isEmpty()){
            trace = Util.newTraceClient()
            locationDao.insertSyncTrace(trace)
        }
        return trace
    }


    

    override fun onLocationChanged(location: Location) {
        Log.d("NetTraceListener", "onLocationChanged: $location $syncTraceId")
        MainScope().launch {
            withContext(Dispatchers.IO) {
                val trace = getSyncTrace()
                // 防止重复发送
                if (trace.traceId == syncTraceId) {
                    Log.d("NetTraceListener", "traceId == syncTraceId $syncTraceId")
                    return@withContext
                }
                syncTraceId = trace.traceId
                try {
                    while(true) {
                        val list = locationDao.getNewLocation(trace.traceId)
                        if (list.isEmpty()) {
                            break
                        }
                        //将list转换为json字符串
                        // 使用StringBuilder
                        val listStr = StringBuilder("{\"trace\":[")
                        for (item in list) {
                            listStr.append(item.toJson()).append(",")
                        }
                        //去掉最后一个逗号
                        listStr.deleteCharAt(listStr.length - 1)
                        listStr.append("]}")

                        //发送数据到服务器
                        // 使用POST请求发送数据到服务器
                        val url = "http://www.xinyu126.com/api/child.trace/pushTrace"
                        val client = OkHttpClient()
                        val clientid = trace.clientId
                        val request = Request.Builder()
                            .url(url)
                            .header("client-id", clientid)
                            .post(
                                listStr.toString()
                                    .toRequestBody("application/json".toMediaTypeOrNull())
                            )
                            .build()
                        Log.d("NetTraceListener", "发送数据到服务器: $listStr")
                        val response = client.newCall(request).execute()

                        if (response.isSuccessful) {
                            Log.d("NetTraceListener", "数据发送成功")
                            val responseBody = response.body?.string()
                            Log.d("NetTraceListener", "服务器返回数据: $responseBody")
                            if (responseBody == null) {
                                break
                            }
                            val json = JSONObject(responseBody)
                            if (json.getInt("code") != 1) {
                                break
                            }
                            val nTraceId =
                                json.getJSONObject("data").getLong("location_id")
                            if (nTraceId > trace.traceId) {
                                trace.traceId = nTraceId
                                locationDao.updateSyncTrace(trace)
                                Log.d("NetTraceListener", "更新traceId: $nTraceId")
                            }else{
                                break
                            }
                        } else {
                            Log.d("NetTraceListener", "数据发送失败: ${response.code}")
                        }
                    }
                } catch (e: Exception) {
                    Log.d("NetTraceListener", "数据发送失败: ${e.message}")
                }finally {
                    syncTraceId = 0
                    Log.d("NetTraceListener", "重置同步ID")
                }
            }
        }
    }
}